package listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * HttpSessionListener接口用来监听HttpSession对象的创建和销毁
 * @author xn
 *
 */
@WebListener
public class OnlineListener implements HttpSessionListener {
    private int count = 0; // 用于统计在线人数变量
    //监听HttpSession对象的创建
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        count++; // Session对象创建时count变量加1
        ServletContext context = event.getSession().getServletContext();
        context.setAttribute("count", count);
    }
    //监听HttpSession对象的销毁
    @Override
    public void sessionDestroyed(HttpSessionEvent hse) {
        count--; // Session对象销毁时count变量减1
        ServletContext context = hse.getSession().getServletContext();
        context.setAttribute("count", count);
    }
}
